package com.main.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

public class PropertiesRead {

	/**
	 * 读取配置文件内容
	 * @param fileName
	 * @return
	 */
	public String getFileContent(String fileName){
		if(null==fileName){
			return null;
		}
		String path=PropertiesRead.class.getResource("/").toString().substring(6)+"config/";
        if(!fileName.toLowerCase().endsWith(".properties")){
        	fileName+=".properties";
        }
        try {
        	InputStream is=new FileInputStream(path+fileName);
        	InputStreamReader ir=new InputStreamReader(is,"UTF-8");
			BufferedReader br=new BufferedReader(ir);
			StringBuilder sb=new StringBuilder();
			String data=null;
			while(null!=(data = br.readLine())){
				sb.append(data+"\r\n");
			}
			is.close();
			ir.close();
			br.close();
			return sb.toString();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 读取配置文件内容
	 * @param fileName
	 * @return
	 */
	public void saveFileContent(String fileName,String content){
		if(null==fileName){
			return;
		}
		String path=PropertiesRead.class.getResource("/").toString().substring(6)+"config/";
        if(!fileName.toLowerCase().endsWith(".properties")){
        	fileName+=".properties";
        }
        try {
        	FileOutputStream fs=new FileOutputStream(path+fileName);
            OutputStreamWriter  ow=new OutputStreamWriter(fs,"UTF-8");
			BufferedWriter bw=new BufferedWriter(ow);
			bw.write(content);
			bw.close();
			ow.close();
			fs.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return;
	}
	
	/**
	 * 获取配置文件文件名
	 * @return
	 */
	public String[] getFileNameList(){
		String path=PropertiesRead.class.getResource("/").toString().substring(6)+"config/";
		File parent=new File(path);
		if(parent.isDirectory()){
			String names[]=parent.list(new FilenameFilter() {
				@Override
				public boolean accept(File dir, String name) {
					if(name.toLowerCase().endsWith(".properties"))
						return true;
					return false;
				}
			});
			
			return names;
		}
		return null;
	}
}
